package com.xdj.iot.util.excelUtils;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;

/**
 * created by chongyahhh
 * 2020/2/21
 */
public class ExcelUtil {

    /**
     * 获取 excel 文件创造器
     * @param excelFileName -> excel 文件的名字
     * @return
     */
    public static ExcelWorkBookCreator getExcelWorkBookCreator(String excelFileName){
        return new ExcelWorkBookCreator(excelFileName);
    }

    /**
     * 列宽自适应，可以在 ExcelProcessor 的实现类的后置处理中使用
     * @param excelAssistBean
     * @param currentSheet
     * @param firstRowNum
     */
    public static void RowWidthAutoFix(ExcelAssistBean excelAssistBean, HSSFSheet currentSheet, int firstRowNum){
        int columnNum = excelAssistBean.getOrderedTitles().size();
        int columnLength = currentSheet.getLastRowNum() + 1;
        System.out.println(columnLength);
        int[] columnWidth = new int[columnNum];
        for(int index = 0;index < columnNum;index++){
            columnWidth[index] = 0;
        }
        HSSFRow currentRow;
        for(int currentRowNum = firstRowNum;currentRowNum < columnLength;currentRowNum++){
            currentRow = currentSheet.getRow(currentRowNum);
            HSSFCell currentCell;
            if(currentRow != null){
                for(int currentColumnNum = 0;currentColumnNum < columnNum;currentColumnNum++){
                    currentCell = currentRow.getCell(currentColumnNum);
                    if(currentCell != null && currentCell.getStringCellValue().getBytes().length > columnWidth[currentColumnNum]){
                        columnWidth[currentColumnNum] = currentCell.getStringCellValue().getBytes().length;
                    }
                }
            }
        }
        for(int index = 0;index < columnNum;index++){
            currentSheet.setColumnWidth(index,columnWidth[index] * 300);
        }
    }

}
